# -*- coding: utf-8 -*-
from flask import request
from flask_restx import Resource, Namespace, fields

from app.models.commodity import Commodity
from utils.response import ResponseMaker
from app.models.user import User
from app.extentions import db
from utils.jwt import JWTUtil

from app.models.commodity import Commodity


commodity_api = Namespace("commodity", description="商品", path="/api/commodity")

commodity_list_model = commodity_api.model('CommodityListModel', {
    'page_number': fields.Integer(required=True, description='页码', default=1),
    'page_size': fields.Integer(required=True, description='每页数量', default=10),
    'keyword': fields.String(required=False, description='查询关键字，根据商品名称进行搜索'),
})

commodity_list_apimodel = commodity_api.model('CommodityListModel', {
    'page_number': fields.Integer(required=True, description="page number", default=1),
    'page_size': fields.Integer(required=True, description="page size", default=10),
    'keyword': fields.String(required=False, description="key word"),
})


@commodity_api.route('/list')
class CommodityListAPI(Resource):

    @commodity_api.doc(description='商品列表', body=commodity_list_model)
    def post(self):
        data = request.get_json(force=True)
        page_number = data.get("page_number")
        page_size = data.get("page_size")
        keyword = data.get("keyword")

        query = Commodity.query
        if keyword:
            query = query.filter(Commodity.name.like("%" + keyword + "%"))

        total = query.count()
        data_objs = query.paginate(page=page_number, per_page=page_size, error_out=False)
        data_obj_list = data_objs.items
        data_list = [item.serialize() for item in data_obj_list]

        resp_data = {
            "total": total,
            "data": data_list
        }

        return ResponseMaker.success(data=resp_data)


@commodity_api.route('/<id>')
class CommodityDetailAPI(Resource):

    @commodity_api.doc(description='商品详情', args={'id': "商品id"})
    def get(self, id):
        commodity_id = int(id)
        commodity = Commodity.query.get(commodity_id)
        if not commodity:
            return ResponseMaker.not_exist(f"商品id: {commodity_id}")

        return ResponseMaker.success(data=commodity.serialize())
